#include <Config.h>
#include "osa.h"
#include "OSAcfg.h"
#include "drv_uart_new.h"
#include "service/osa_bsem.h"
#include "service/osa_qmsg.h"
#include "my_osa_init.h"
#include "Rs485.h"



int TX_ByteNumber;
int RX_ByteNumber;
int 	TX_len;
int 	RX_len;


void __attribute__((__interrupt__,auto_psv))   _T1Interrupt( void) 
{

	//100 ms tick
	PR1 = 25000-1;
 	OS_Timer();
	
	_T1IF = 0;
	
	
} //T1Interrupt


void __attribute__((__interrupt__,auto_psv))    _OscillatorFail ( void) 
{

	while (1);	
} 

void __attribute__((__interrupt__,auto_psv))    _StackError ( void) 
{
	while (1);
}  

void __attribute__((__interrupt__,auto_psv))   _MathError ( void) 
{
while (1);
}  


/**********************************************************************
 * Part of the transmiter interrupt routine.
 *
 **********************************************************************/
void __attribute__((__interrupt__,auto_psv)) _U1TXInterrupt(void)
{   
	char temp;
	temp = OS_DI ();
	IFS0bits.U1TXIF = 0;
	if ((TX_ByteNumber > 0) && (TX_ByteNumber  < TX_len))
	{
		while(U1STAbits.UTXBF);
		U1TXREG = (unsigned char) strPacket[TX_ByteNumber];
	}
	if (TX_ByteNumber   == (TX_len))
	{
		IEC0bits.U1TXIE = 0;
		TX_ByteNumber = -1;
	}
	TX_ByteNumber++;
	OS_RI ( temp);
	return;
}

/**********************************************************************
 * Part of the receiver interrupt routine.
 *
 **********************************************************************/
void __attribute__((__interrupt__,auto_psv)) _U1RXInterrupt(void)
{
	char temp;
	temp = OS_DI ();

	IFS0bits.U1RXIF = 0;
	// A length is expected
	if ((RX_ByteNumber >= 0) && (RX_ByteNumber< RX_len))
		drv_rs485_msg_rx[RX_ByteNumber] = U1RXREG;
	if (RX_ByteNumber == (RX_len) - 1)
		{
			OS_SetBSem(RS_QUEUE_FULL);
			RX_ByteNumber = -1;
		}
		RX_ByteNumber++;
	
	// A special character is expected
//	else
//	{
//		RS_list_head_rcv->data[RX_ByteNumber] = U1RXREG;
//		if (RS_list_head_rcv->pattern == RS_list_head_rcv->data[RX_ByteNumber])
//		{
//			OS_SetBSem(RS_QUEUE_FULL);
//			RX_ByteNumber = -1;
//		}
//		RX_ByteNumber++;
//	}
	OS_RI (temp);
	return;
}

